<template>
  <div class="wrap">
    <el-tabs
      :tab-position="tabPosition"
      v-model="activeName"
      style="height: 200px;"
      @tab-click="handleClick"
    >
      <!-- 博主信息 -->
      <el-tab-pane label name="5">
        <span slot="label">
          <span class="span-box">
            <span>博主 ：</span>
            <i class="fa fa-user-circle"></i>
          </span>
        </span>
        <div class="about">
          <img
            class="myImg"
            width="200px"
            height="200px"
            src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1591633641470&di=2cc93c6880d84fb7fc5ff57845ce200f&imgtype=0&src=http%3A%2F%2Fimg1.juimg.com%2F180409%2F355843-1P40910300930.jpg"
            alt
          />
          <div>
            <a href="https://github.com/Helsink-z" class="fa fa-github"></a>
            <el-popover placement="top-start" width="50" trigger="hover">
              <img
                width="150px"
                height="100px"
                src="http://img.haote.com/upload/qrcode/1339/haote31ca2e8f449f4dc0a601feca11584866.png"
                alt
              />
              <span slot="reference">
                <i class="fa fa-weixin" style="font-size:36px"></i>
              </span>
            </el-popover>
            <el-popover placement="top-start" width="50" trigger="hover">
              <img
                width="150px"
                height="100px"
                src="http://img0.pconline.com.cn/pconline/1403/10/4412496_03_thumb.jpg"
                alt
              />
              <span slot="reference">
                <i class="fa fa-qq" style="font-size:36px"></i>
              </span>
            </el-popover>
          </div>
          <el-divider></el-divider>
          <p class="myIntroduction">
            作者简介:
            Hi,everyone!Letmeintroducemyself.
            Let'sknoweachother.
            IwasborninLiaoning.Liaoningisabeautifulplace.
            TherearemanyplacesofinterestinLiaoning.
            IwasbornonSeptember,26th.Iamagirl.
            Iliketraveling,readingandEnglish.
            SpeakingEnglishisveryimportant.
            It'sveryusefulforus.WeshoulddoourbesttolearnEnglish.Ilikemakingfriends,too.
            Iwanttomakemoreandmorefriends.
            Let'sbefriends.WhenIamfree,...”
          </p>
          <div class="attachMe"></div>
        </div>
      </el-tab-pane>
      <!-- 写博客 -->
      <el-tab-pane label name="1">
        <span slot="label">
          <span class="span-box">
            <span>写博客 ：</span>
            <i class="fa fa-edit (alias)"></i>
          </span>
        </span>
        <div class="writeBlog">
          <el-form label-width="120px">
            <el-form-item label="为博客添加页码">
              <el-input type="text" v-model="page" width="200"></el-input>
            </el-form-item>
            <el-form-item label="为博客添加标题">
              <el-input type="text" v-model="title" width="200"></el-input>
            </el-form-item>
            <el-form-item label="为草稿添加标题">
              <el-input type="text" v-model="draftTitle" width="200"></el-input>
            </el-form-item>
          </el-form>
          <!-- 添加标签 -->
          <div class="setTag">
            <i class="fa fa-tags"></i>
            <div @click="showTagsValue">
              <el-tag v-for="(item,index) in tagNames" :key="item.index">{{item.tagName}}</el-tag>
            </div>
          </div>
          <!-- 富文本编辑器 -->
          <div class="editor">
            <div ref="toolbar" class="toolbar"></div>
            <div ref="editor" class="text"></div>
          </div>
          <el-button @click="loadDraft">展示草稿</el-button>
          <el-button @click="loadModifyBlog">展示将要修改的博客</el-button>
          <el-button @click="send">发表博客</el-button>
          <el-button @click="save">保存到草稿箱</el-button>
          <el-backtop>
            <i class="fa fa-angle-double-up"></i>
          </el-backtop>
        </div>
      </el-tab-pane>
      <!-- 草稿 -->
      <el-tab-pane label name="2">
        <span slot="label">
          <span class="span-box">
            <span>草稿 ：</span>
            <i class="fa fa-file-word-o"></i>
          </span>
        </span>
        <div v-for="(item,index) in draft" :key="index" class="draft">
          <el-row>
            <el-col :span="2">{{index+1}}</el-col>
            <el-col :span="10">{{item.draftTitle}}</el-col>
            <el-col :span="12">
              <el-button @click="childClick(item)">
                <i class="fa fa-check"></i>继续编辑
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <!-- 删除评论 -->
      <el-tab-pane label name="3">
        <span slot="label">
          <span class="span-box">
            <span>评论管理 ：</span>
            <i class="fa fa-commenting"></i>
          </span>
        </span>
        <div class="userComments" v-for="(item,index) in getAllComments" :key="index">
          <div class="userInfo">
            <el-row>
              <el-col :span="4" class="title">
                <p>{{item.title}}</p>
              </el-col>
              <el-col :span="8">
                <img :src="item.userImg" alt width="50px" height="50px" />
                <span>{{item.userName}}</span>
              </el-col>
              <el-col :span="10">
                <p>{{item.content}}</p>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" @click="deletecomments(item)">
                  <i class="fa fa-remove (alias)"></i>
                  删除
                </el-button>
              </el-col>
            </el-row>
          </div>
          <div
            class="replyComment"
            v-if="item.reply"
            v-for="(items,index) in item.reply"
            :key="index"
          >
            <el-row>
              <el-col :span="10">
                <p>{{items.replyUserName}} 回复了 {{item.userName}}</p>
              </el-col>
              <el-col :span="10">
                <p>{{items.content02}}</p>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-tab-pane>
      <!-- 所有文章 -->
      <el-tab-pane label name="4">
        <span slot="label">
          <span class="span-box">
            <span>所有文章 ：</span>
            <i class="fa fa-book"></i>
          </span>
        </span>
        <div class="blogWrap" v-for="(item,index) in data" :key="index">
          <el-row>
            <el-col :span="2">{{index+1}}</el-col>
            <el-col :span="14">
              <router-link to="/detail" class="blogTitle">
                <div @click="setlocal(item)">{{item.title}}</div>
              </router-link>
            </el-col>
            <el-col :span="4">
              <el-button @click="modifyBlog(item)">修改</el-button>
            </el-col>
            <el-col :span="4">
              <el-button @click="deleteBlog(item)">
                <i class="fa fa-remove (alias)"></i>删除
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
      <!-- 标签管理 -->
      <el-tab-pane label name="6">
        <span slot="label">
          <span class="span-box">
            <span>标签管理 ：</span>
            <i class="fa fa-tags"></i>
          </span>
        </span>
        <div>
          <el-button @click="addTags">
            <i class="fa fa-check"></i>添加标签
          </el-button>
          <el-input v-model="tagName" class="tagInput"></el-input>
        </div>
        <!-- 删除标签 -->
        <el-button type="text" @click="dialogVisible = true">
          <div class="delTags">
            <div>
              <el-button>
                <i class="fa fa-remove (alias)"></i>删除标签
              </el-button>
            </div>
            <div class="setTag">
              <i class="fa fa-tags"></i>
              <div @click="showTagsValue">
                <el-tag v-for="(item,index) in tagNames" :key="item.index">{{item.tagName}}</el-tag>
              </div>
            </div>
          </div>
        </el-button>

        <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
          <span>是否要删除标签</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="delTags">确 定</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import axios from "axios";
import E from "wangeditor";

export default {
  name: "editoritem",
  data() {
    return {
      tabPosition: "top", //标签页位置
      getAllComments: "", //获取评论
      activeName: "5", //将要展示的标签页
      newBlog: Number,
      newBlogTitle: [],
      data: "",
      draft: "", //写博客
      editor: null, //富文本编辑器
      info_: '', //富文本编辑器内容
      sort: "", //博客分类标签
      page: "", //页码
      title: "", //博客标题
      draftTitle: "", //草稿标题
      newBlogTitle: [], //新博客标题
      ceshi: "", //向富文本展示将要操作的内容
      tagNames: "", //标签名
      tagName: "", //将要添加的标签名
      dialogVisible: false, //是否显示对话框
      gonnaDelTagName: ""
    };
  },
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {
      type: String,
      default: ""
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear();
        this.info_ = null;
      }
    },
    value: function(value) {
      if (value !== this.editor.txt.html()) {
      }
    }
    //value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
  },
  mounted() {
    this.seteditor();
    this.editor.txt.html(this.ceshi);
    //草稿页面
    axios({
      url: "http://localhost:3000/admin/getdraft",
      method: "get"
    }).then(response => {
      this.draft = response.data.message;
    });
    //首次加载获取所有评论
    axios({
      url: "http://localhost:3000/admin/getallcomments",
      method: "get"
    }).then(response => {
      if (response) {
        this.getAllComments = response.data.message;
      } else {
        console.log("无评论");
      }
    });
    //获取所有博客
    axios({
      url: "http://localhost:3000/admin/getallblogs",
      method: "get"
    }).then(response => {
      this.data = response.data.message;
      console.log(this.data);
    });
    //获取标签
    axios({
      url: "http://localhost:3000/admin/gettags",
      method: "get"
    }).then(response => {
      this.tagNames = response.data.message;
    });
  },
  methods: {
    //删除评论
    deletecomments(item) {
      axios({
        url: "http://localhost:3000/admin/deletecomments",
        method: "post",
        data: { content: item.content }
      }).then(response => {
        if (response) {
          this.getAllComments = response.data.message;
          this.$message.success("删除评论成功，快去前台看看吧！");
        } else {
          this.$message.fail("无评论可以删除");
        }
      });
    },
    //删除博客
    deleteBlog(item) {
      axios({
        url: "http://localhost:3000/admin/deleteblog",
        method: "post",
        data: { title: item.title }
      }).then(response => {
        this.$message.success("删除博客成功，刷新一下！");
      });
    },
    //修改博客
    modifyBlog(item) {
      this.activeName = "1";
      sessionStorage.modifyTitle = item.title;
      axios({
        url: "http://localhost:3000/admin/getonemodifyblog",
        method: "post",
        data: { title: item.title }
      }).then(response => {
        this.ceshi = response.data.message.test;
        this.$message.success("您可以修改了");
      });
    },
    handleClick(tab, event) {},
    //添加草稿到修改页面
    childClick(item) {
      this.activeName = "1";
      axios({
        url: "http://localhost:3000/admin/getonedraft",
        method: "post",
        data: { draftTitle: item.draftTitle }
      }).then(response => {
        this.ceshi = response.data.message.draftContent;
        this.$message.success("添加草稿成功");
      });
    },
    //下面是写博客页面的方法
    seteditor() {
      this.editor = new E(this.$refs.toolbar, this.$refs.editor);
      this.editor.customConfig.uploadImgShowBase64 = false; // base 64 存储图片
      this.editor.customConfig.uploadImgServer =
        "http://otp.cdinfotech.top/file/upload_images"; // 配置服务器端地址
      this.editor.customConfig.uploadImgHeaders = {}; // 自定义 header
      this.editor.customConfig.uploadFileName = "file"; // 后端接受上传文件的参数名
      this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      this.editor.customConfig.uploadImgMaxLength = 6; // 限制一次最多上传 3 张图片
      this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000; // 设置超时时间

      // 配置菜单
      this.editor.customConfig.menus = [
        "head", // 标题
        "video", // 插入视频
        "image", // 插入图片
        "undo", // 撤销
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "italic", // 斜体
        "underline", // 下划线
        "strikeThrough", // 删除线
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "link", // 插入链接
        "list", // 列表
        "justify", // 对齐方式
        "quote", // 引用
        "emoticon", // 表情
        "table", // 表格
        "code", // 插入代码
        "redo" // 重复
        // "fullscreen" // 全屏
      ];

      this.editor.customConfig.uploadImgHooks = {
        fail: (xhr, editor, result) => {
          // 插入图片失败回调
        },
        success: (xhr, editor, result) => {
          // 图片上传成功回调
        },
        timeout: (xhr, editor) => {
          // 网络超时的回调
        },
        error: (xhr, editor) => {
          // 图片上传错误的回调
        },
        customInsert: (insertImg, result, editor) => {
          // 图片上传成功，插入图片的回调
          //result为上传图片成功的时候返回的数据，这里我打印了一下发现后台返回的是data：[{url:"路径的形式"},...]
          // console.log(result.data[0].url)
          //insertImg()为插入图片的函数
          //循环插入图片
          // for (let i = 0; i < 1; i++) {
          // console.log(result)
          let url = "http://otp.cdinfotech.top" + result.url;
          insertImg(url);
          // }
        }
      };
      this.editor.customConfig.onchange = html => {
        this.info_ = html; // 绑定当前逐渐地值
        this.$emit("change", this.info_); // 将内容同步到父组件中
      };
      // 创建富文本编辑器
      this.editor.create();
    },
    //发表博客
    send() {
      console.log(this.info_);
      
      localStorage.newBlog = parseInt(localStorage.newBlog) + 1;
      sessionStorage.newBlogTitle = sessionStorage.newBlogTitle + this.title;
      const data = {
        test: this.info_,
        sort: localStorage.sort,
        page: this.page,
        title: this.title
      };
      localStorage.info_ = JSON.stringify(this.info_);
      axios({
        url: "http://localhost:3000/admin/publish",
        method: "post",
        data: data
      }).then(response => {
        this.$message.success("发表博客成功，快去前台看看吧！");
      });
    },
    //写博客页面展示标签
    showTagsValue(e) {
      localStorage.sort = e.target.innerHTML;
      this.gonnaDelTagName = e.target.innerHTML;
      console.log(this.gonnaDelTagName);
    },
    //保存博客到草稿箱数据库
    save() {
      const data = {
        draftContent: this.info_,
        draftTitle: this.draftTitle
      };
      localStorage.info_ = JSON.stringify(this.info_);
      axios({
        url: "http://localhost:3000/admin/savetodraft",
        method: "post",
        data: data
      }).then(response => {
        this.$message.success("保存博客成功，快去数据库看看吧！");
      });
    },
    //测试函数
    test() {
      axios({
        url: "http://localhost:3000/admin/test",
        method: "get"
      }).then(response => {
        const a = JSON.stringify(response.data.message[8].test);
        this.info_ = JSON.parse(a);
        this.editor.txt.append("this.info_");
      });
    },
    //展示草稿
    loadDraft() {
      this.editor.txt.html(this.ceshi);
    },
    //展示将要修改的博客
    loadModifyBlog() {
      this.editor.txt.html(this.ceshi);
    },
    //添加标签
    addTags() {
      axios({
        url: "http://localhost:3000/admin/addtags",
        method: "post",
        data: { tagName: this.tagName }
      }).then(response => {
        console.log(response);
      });
    },
    //删除标签
    delTags(e) {
      console.log(this.gonnaDelTagName);

      axios({
        url: "http://localhost:3000/deltags",
        method: "post",
        data: { tagName: this.gonnaDelTagName }
      }).then(response => {
        console.log(response);
        this.dialogVisible = false;
      });
    },
    //处理关闭前的对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
  }
};
</script>
<style>
html,
body,
#app,
.wrap,
.el-container {
  /*设置内部填充为0，几个布局元素之间没有间距*/
  padding: 0px;
  /*外部间距也是如此设置*/
  margin: 0px;
  /*统一设置高度为100%*/
  height: 100%;
  /* 只要让所有父级元素高度设置100%，然后子元素高度100%就会撑满全屏 */
}
.writeBlog {
  width: 90%;
  background: whitesmoke;
  margin: 0 auto;
}
.el-aside > ul > li {
  list-style: none;
}
.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 100px;
}
.el-col-14 > a {
  text-decoration: none;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  /* line-height: 160px; */
}
.blogWrap {
  background: whitesmoke;
}
.blogWrap .el-col-16 > a {
  text-decoration: none;
}
.el-form {
  width: 50%;
}
.draft {
  width: 80%;
  margin: 0 auto;
  /* background: whitesmoke; */
}
/* 评论 */
.showComments {
  line-height: 1rem;
  background: skyblue;
}
.userComments {
  background: whitesmoke;
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  width: 50rem;
  margin: 1px auto;
}
.replyComment {
  background: whitesmoke;
  margin-top: 1px;
}
.administer > img {
  width: 20rem;
  height: 20rem;
}
.administer > img {
  border-radius: 50%;
}
.userInfo {
  margin: 0 auto;
  width: 80%;
}
/* 这是富文本插件页面的标签样式 */
.setTag {
  display: flex;
}
.setTag > div {
  line-height: 3rem;
}
/* 富文本 */
.editor {
  text-align: center;
  height: 100%;
  margin-bottom: 13rem;
}
/* 博主信息 */
.about {
  width: 50%;
  margin: 0 auto;
  height: 500px;
}
.about > img {
  border-radius: 50%;
}
/* 标签的输入框 */
.tagInput {
  width: 10rem;
}
.delTags {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
.title {
  background: cornflowerblue;
}
.fa-github {
  text-decoration: none;
  color: black;
  font-size: 38px;
}
</style>